package com.sfx.other.JVM.ClassLoader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-05
 * Time: 9:56
 */
public class MyClassLoader extends ClassLoader {
    /**
     * 1. 继承 ClassLoader 父类
     * 2. 要遵从双亲委派机制，重写 findClass 方法
     * 注意不是重写 loadClass 方法，否则不会走双亲委派机制
     * 3. 读取类文件的字节码
     * 4. 调用父类的 defineClass 方法来加载类
     * 5. 使用者调用该类加载器的 loadClass 方法
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String path = "D:\\classpath\\" + name + ".class";
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Files.copy(Paths.get(path),os);
            byte[] bytes = os.toByteArray();
            return defineClass(name,bytes,0,bytes.length);

        } catch (IOException e) {
            System.out.println("找不到该类 : " + name);
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> mapImpl1 = myClassLoader.loadClass("mapImpl");
        System.out.println(mapImpl1);
        Scanner scanner = new Scanner(System.in);
        Float f = 1.0f;

    }
}